import React, { useState, useEffect } from "react";
import {
  message,
  Drawer,
  Form,
  Input,
  Button,
  Row,
  Col,
  TreeSelect,
  Upload,
  Radio,
  InputNumber,
} from "antd";
import local from "@/utils/local";
import {
  addField,
  upadataField,
  cmsColumnAllTree,
  cmsTemplateList,
  getDetail,
} from "../api";
import styles from "../index.less";

const { SHOW_ALL } = TreeSelect;

/**
 * @zh-CN 栏目同步树格式化
 *
 * @param datas
 */

const setColumnTreeFormat = (datas) => {
  const newData = [];
  datas.map((item) => {
    const obj = {
      id: item.columnId,
      value: item.columnId,
      pId: item.parentId,
      title: item.columnName,
    };
    if (item.children && item.children.length) {
      obj.children = setColumnTreeFormat(item.children);
    }
    newData.push(obj);
    return "";
  });
  return newData;
};

const UpdateForm = (props) => {
  // 结构化数据
  const { visible, onCancel, onSuccess, data, type, siteId, currentIndex } =
    props;

  // 初始化 form
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const [fileList, setFileList] = useState([]);

  const [column, setColumn] = useState(); //  栏目
  const [cmsColumnAllTreeData, setcmsColumnAllTreeData] = useState([]); // 栏目同步树
  const [columnImg, setColumnImg] = useState();

  // const [templateId, setTemplateId] = useState(); //  模板
  const [cmsTemplateListData, setcmsTemplateListData] = useState([]); // 模板

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  // 详情
  const getDetailData = () => {
    getDetail(data.columnId).then((res) => {
      if (res.code === 0) {
        if (data.imageUrl) {
          setFileList([
            {
              uid: `tmp-${1}`,
              name: "栏目图片",
              // eslint-disable-next-line no-undef
              url: `${baseUrl}${data.imageUrl}`,
              postUrl: data.imageUrl,
              status: "done",
            },
          ]);
        } else {
          setFileList([]);
        }

        setColumn(data.parentId);
        form.setFieldsValue({ ...data, templateId: res.data.templateId });
      } else {
        message.error(res.msg || "获取详情失败");
      }
    });
  };

  /**
   * @zh-CN 同步获取栏目树
   *
   * @param fields
   */
  const getcmsColumnAllTree = async () => {
    try {
      const res = await cmsColumnAllTree(siteId);
      if (res.code === 0) {
        setcmsColumnAllTreeData(setColumnTreeFormat(res.data));
        return;
      }
    } catch (error) {
      message.error("获取站点失败，请重试");
      return false;
    }
  };

  /**
   * @zh-CN 模板列表
   *
   * @param fields
   */
  const getCmsTemplateList = async (fields) => {
    try {
      const res = await cmsTemplateList({ ...fields });
      if (res.code === 0) {
        setcmsTemplateListData(res.data);
        return;
      }
    } catch (error) {
      message.error("获取模板失败，请重试");
      return false;
    }
  };

  // 选择栏目
  const columnOnChange = (value) => {
    setColumn(value);
  };

  useEffect(() => {
    setColumn();
    setFileList([]);
    setcmsColumnAllTreeData([]);
    getcmsColumnAllTree();
    if (cmsTemplateListData.length === 0 && visible) {
      getCmsTemplateList();
    }

    if (type === "updata" && visible === true) {
      getDetailData();
    } else {
      form.resetFields();
    }
    form.setFieldsValue({ orderNum: currentIndex });
  }, [visible]);

  const accessToken = local.get("token");

  const coverImageProps = {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
    showUploadList: true,
    listType: "picture-card",
    fileList,
    data: { businessType: "cms", fileName: "fileName" },
    // eslint-disable-next-line no-undef
    action: `${API_PREFIX}/upload`,
    onChange: ({ fileList: newFileList }) => {
      setFileList(newFileList);
    },
    accept: "image/gif,image/jpeg,image/png",
    multiple: 1,
  };

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = (values, imageUrl) => {
    const hide = message.loading("正在添加");
    setLoading(true);
    values.img = null;
    upadataField({
      ...values,
      columnId: data.columnId,
      parentId: column,
      imageUrl,
    }).then((res) => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || "修改失败，请重试");
      }
    });
  };
  /**
   * @en-US Update node
   * @zh-CN 添加
   * @param values
   */
  const addData = (values, imageUrl) => {
    const hide = message.loading("正在添加");
    setLoading(true);
    values.img = null;
    addField({ ...values, parentId: column, imageUrl }).then((res) => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || "添加失败，请重试");
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then((values) => {
      values.siteId = siteId;
      const imageUrl =
        fileList[0]?.response?.data?.fileUrl || fileList[0]?.postUrl;
      if (type === "updata") updataData(values, imageUrl);
      if (type === "add") addData(values, imageUrl);
    });
  };

  const modelClose = () => {
    onCancel(false);
  };

  return (
    <>
      <Drawer
        getContainer={false}
        width={640}
        title={type === "updata" ? "修改" : "添加"}
        visible={visible}
        zIndex={1000000}
        onClose={modelClose}
        maskClosable={false}
        footer={
          <div
            style={{
              textAlign: "right",
            }}
          >
            <Button onClick={modelClose} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button
              onClick={sendData}
              type="primary"
              loading={loading}
              disabled={loading}
            >
              保存
            </Button>
          </div>
        }
      >
        <Form {...formItemLayout} name="control-ref" form={form}>
          {visible && (
            <div className={styles.treeBox}>
              <Row>
                <Col span={14} push={4}>
                  <TreeSelect
                    treeData={cmsColumnAllTreeData}
                    placeholder="父级栏目"
                    value={column}
                    style={{ width: 340 }}
                    showSearch
                    onChange={(value, label, extra) => {
                      columnOnChange(value, label, extra);
                    }}
                    allowClear
                  />
                </Col>
                <Col span={4} pull={14}>
                  <div className={styles.treeName}>父级栏目：</div>
                </Col>
              </Row>
            </div>
          )}
          <Form.Item
            label="栏目名称"
            name="columnName"
            rules={[{ required: true }]}
          >
            <Input maxLength={20} allowClear />
          </Form.Item>
          <Form.Item label="栏目图片">
            <Form.Item name="img" noStyle>
              <Upload name="file" {...coverImageProps}>
                {fileList.length < 1 && <>Upload</>}
              </Upload>
            </Form.Item>
          </Form.Item>
          <Form.Item
            width="xs"
            name="orderNum"
            label="显示顺序"
            rules={[{ required: true }]}
          >
            <InputNumber min={0} max={1000} />
          </Form.Item>
          <Form.Item
            name="templateId"
            label="选择模板"
            rules={[{ required: true }]}
          >
            <Radio.Group>
              {cmsTemplateListData.map((item) => (
                <div className={styles.temsBox} key={item.templateId}>
                  <Radio value={item.templateId * 1}>
                    <p>{item.templateName}</p>
                    {item.templateImg.split(",") &&
                      item.templateImg.split(",")[0] && (
                        <img
                          src={`${baseUrl}${item.templateImg.split(",")[0]}`}
                          style={{ width: 100, marginRight: 10 }}
                        />
                      )}
                    {item.templateImg.split(",") &&
                      item.templateImg.split(",")[1] && (
                        <img
                          src={`${baseUrl}${item.templateImg.split(",")[1]}`}
                          style={{ width: 100 }}
                        />
                      )}
                  </Radio>
                </div>
              ))}
            </Radio.Group>
          </Form.Item>
        </Form>
      </Drawer>
    </>
  );
};

export default UpdateForm;
